//
//  UserMessageListController.m
//  NiuBanGold
//
//  Created by Billy on 15/12/8.
//  Copyright © 2015年 zzjr. All rights reserved.
//

#import "UserMessageListController.h"
#import "MessageCell.h"
#import "DetailMessageViewController.h"

@interface UserMessageListController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;//展示数据源
@property (nonatomic, strong) NSMutableArray *mutableArray_allMessages;

@property (nonatomic, strong) MBProgressHUD *hud;

@property (nonatomic, assign) int pageNumber;// 当前刷新的页数，默认从1开始

@end

@implementation UserMessageListController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self pageSettingsAndSubviewsCreation];
    
    [self setRightAndLeftBarButton];
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    self.pageNumber = 1;
    [self getDataFromServer];
}

#pragma mark - data preparation

- (void) getDataFromServer {
    
    NSDictionary *dic_Params = @{@"userId":GETCURRENTUSERINOBYPRAMETERES(user_userId),@"token":GETCURRENTUSERINOBYPRAMETERES(user_userToken),@"offSet":[NSString stringWithFormat:@"%d",self.pageNumber]};
    
    [self.hud show:YES];
    
    [[NetworkUtil sharedNetworkUtil] zzjr_getUserMessageListByParmeteres:dic_Params transferResultUsingBlock:^(id parsedData, NSError *error) {

        [self.hud hide:YES];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        
        if (!error) {
          
            NSDictionary *dic_result = parsedData;
            
            //取得当前数据源
            if (self.pageNumber == 1) {
                
                [self.mutableArray_allMessages removeAllObjects]; //以防万一，去掉历史数据
                
                 self.mutableArray_allMessages = [dic_result objectForKey:@"messageArray"];
                
                if ([self.mutableArray_allMessages count] == 0) { //判定什么时候显示空数据几个字
                    
                    EmptyDataView *view_empty = [[EmptyDataView alloc]initWithFrame:self.tableView.frame];
                    [self.view addSubview:view_empty]; // 加过一次后就永远存在了，要想办法去掉
                    
                    self.pageNumber = 1;
                }else {
                    
                    [self.view bringSubviewToFront:self.tableView]; //把tableview放前面就行了，不用remove再加,省资源
                }
            }else { //不是第一页的时候保留历史数据
                
                NSArray *array_addedData = [dic_result objectForKey:@"messageArray"];

                [self.mutableArray_allMessages addObjectsFromArray:array_addedData];
            }
           
            if ([self.mutableArray_allMessages count] > 0) {
                
                [self.tableView reloadData];
                
            }else {//没数据时显示为暂无数据,同时隐藏右上角按钮
                
                EmptyDataView *view_empty = [[EmptyDataView alloc] initWithFrame:self.view.frame];
                
                [self.view addSubview:view_empty];
            }
            
        }else {
            
            [UsefulUtil showAlertView:@"遇到网络问题，请稍候重试!"];
        }
    }];
}


#pragma mark - SubviewsCreationAndPageSettings

- (void) pageSettingsAndSubviewsCreation {
    
    [self.view setBackgroundColor:BASECOLOR];
    
    [self.navigationItem setTitle:@"消息中心"];
    
    [self.view addSubview:self.tableView];
    
//    [self setRightAndLeftBarButton]; //用delay loading的办法没有数据时显示为暂无数据
    
    self.pageNumber = 1;
}

- (void) setRightAndLeftBarButton {

    //1. right
    
    UIButton *button_right = [[UIButton alloc] initWithFrame:CGRectMake(0, MULTIPLYHEIGHT(12.0/2), MULTIPLYWIDTH(209/2), MULTIPLYHEIGHT(28.0/2))];

    [button_right setImage:[UIImage imageNamed:@"markRead"] forState:UIControlStateNormal];
    
    UIBarButtonItem *item_right = [[UIBarButtonItem alloc] initWithCustomView:button_right];
    UIBarButtonItem *negativeSpace = [[UIBarButtonItem alloc]
                                      initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                      target:nil action:nil];
    [negativeSpace setWidth:MULTIPLYWIDTH(-15.0)];
    
    [self.navigationItem setRightBarButtonItems:@[item_right]];
    
    //3. add target
    
    [button_right setTag:21];
    
    [button_right addTarget:self action:@selector(buttonEventsHandling:) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark - TableView datasource && delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return [self.mutableArray_allMessages count];
}

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView setRowHeight:MULTIPLYHEIGHT(180.0/2)];
    
    static NSString *identifer = @"cell" ;
    
    MessageCell *cell = [tableView dequeueReusableCellWithIdentifier:identifer];
    
    if (!cell) {
        
        cell = [[MessageCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifer];
    }
    
    [cell setMessage:[self.mutableArray_allMessages objectAtIndex:indexPath.row]];
    
    return  cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    Message *message = [self.mutableArray_allMessages objectAtIndex:indexPath.row];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [self setAllMessageAsReadWithMessageId:message.message_mid];
    });

    //跳转到详情页面 传递message
    
    DetailMessageViewController *detailsVC = [[DetailMessageViewController alloc] init];
    
    [detailsVC setMessage:message];
    
    [detailsVC setHidesBottomBarWhenPushed:YES];
    
    [self.navigationController pushViewController:detailsVC animated:YES];
    
}

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView *view_header = [UsefulUtil viewCreationWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, MULTIPLYHEIGHT(10.0/2)) backgroundColor:BASECOLOR backGroundImage:nil];
    
    return view_header;
}

- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return MULTIPLYHEIGHT(10.0/2);
}

#pragma mark - button events handling

- (void) headerFresh {
    self.pageNumber = 1;
    
    [self getDataFromServer];
    //下拉
}

- (void) footerFresh {

    if ([self.mutableArray_allMessages count] >= 50) {
    
        self.pageNumber++;
    }
    
    [self getDataFromServer];
}


- (void) buttonEventsHandling:(UIButton *) button {
    
    switch (button.tag) {
        case 21: //标记所有的消息为已读
        {
            [self setAllMessageAsReadWithMessageId:@"all"];
        }
            break;
            
        default:
            break;
    }
}

- (void) setAllMessageAsReadWithMessageId:(NSString *) mssageId {
    
    NSDictionary *dic_params = @{@"userId":GETCURRENTUSERINOBYPRAMETERES(user_userId),@"token":GETCURRENTUSERINOBYPRAMETERES(user_userToken),@"mid":mssageId};

    
    [[NetworkUtil sharedNetworkUtil] zzjr_getUserMessageMarkedAsReadByParmeteres:dic_params transferResultUsingBlock:^(id parsedData, NSError *error) {
        
        if (!error) {
            
            NSDictionary *dic = parsedData;
       
            if ([dic[@"status"] integerValue] == 0 ) {
                
                [self getDataFromServer]; //重新加载数据
                
            }else { //服务器出错
                
                [UsefulUtil showAlertView:dic[@"result"][@"msg"]];
            }
            
        }else {
            
            [UsefulUtil showAlertView:@"遇到网络问题，请稍候重试!"];
        }
    }];
}

#pragma mark - Setter method

- (UITableView *)tableView {
    
    if (!_tableView) {
        
        _tableView = [[UITableView alloc] initWithFrame:self.view.frame];
        
        [_tableView setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
        [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
        [_tableView setBackgroundColor:BASECOLOR];
        [_tableView setDelegate:self];
        [_tableView setDataSource:self];
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerFresh)];
        
        // 设置尾部
        _tableView.mj_footer = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerFresh)];
        
    }
    
    return  _tableView;
}

- (MBProgressHUD *)hud {
    
    if (!_hud) {
        
        _hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [_hud setLabelText:@"正在加载..."];
    }
    
    return _hud;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
